package light3d;
import java.io.*;
import java.util.Vector;

public class WavefrontMesh extends BasicMesh 
{
	public WavefrontMesh(String file)
	{    
		super();
		loadMesh(file);
	}
	private void loadMesh(String file)
	{
		Vector<Point3D> tempPoints = new Vector<Point3D>(); 
		Vector<Point3D> normalPoints = new Vector<Point3D>();
		
		try 
		{
			BufferedReader inputStream = new BufferedReader(new FileReader(file));
			String inData;
			while ((inData = inputStream.readLine()) != null) 
			{
				if (inData.length() > 0)
				{
					String[] parts;
					String tc = inData.substring(0, 2);
					if (tc.equals("v "))
					{
						parts = inData.split(" ");
						double x = Double.parseDouble(parts[1]),
							   y = Double.parseDouble(parts[2]),
							   z = Double.parseDouble(parts[3]);
						tempPoints.addElement(new Point3D(x,y,z));
					}
					if (tc.equals("vn"))
					{
						parts = inData.split(" ");
						double x = Double.parseDouble(parts[1]),
							   y = Double.parseDouble(parts[2]),
							   z = Double.parseDouble(parts[3]);
						normalPoints.addElement(new Point3D(x,y,z));
					}
					if (tc.equals("f "))
					{
						parts = inData.split(" ");
						int v1,v2,v3, uv1 = 0, uv2 = 0, uv3 = 0, n1 = 0;
						
						v1 = Integer.parseInt(parts[1].split("/")[0]) - 1;
				    	v2 = Integer.parseInt(parts[2].split("/")[0]) - 1;
				    	v3 = Integer.parseInt(parts[3].split("/")[0]) - 1;
						
						Triangle t1 = new Triangle(BufferedCanvas.getRGBColor(255, 255, 255));
						t1.p[0] = tempPoints.get(v1).clone();
						t1.p[1] = tempPoints.get(v2).clone();
						t1.p[2] = tempPoints.get(v3).clone();

						if (normalPoints.size() > 0)
						{
							n1 = Integer.parseInt(parts[1].split("/")[2]) - 1;							
							t1.setBaseNormal(normalPoints.get(n1));
						}
						else
						{
							t1.computeNormal();
						}
						
						appendTriangle(t1);
						
						if (parts.length==5)
						{
							
							int v4 = Integer.parseInt(parts[4].split("/")[0]) - 1;
							
							Triangle t2 = new Triangle(BufferedCanvas.getRGBColor(255, 255, 255));
							t2.p[0] = tempPoints.get(v1).clone();
							t2.p[1] = tempPoints.get(v3).clone();
							t2.p[2] = tempPoints.get(v4).clone();
							
							if (normalPoints.size() > 0)
							{
								t2.setBaseNormal(normalPoints.get(n1));
							}
							else
							{
								t2.computeNormal();
							}
							
							appendTriangle(t2);
						}
					}
				}
			}
			inputStream.close();
			finalizeMesh();
			System.out.println("LOADED " + file + " of " + triangles.length + " triangles.");
    }
		catch (IOException e) 
		{
			System.out.println("I/O Error Loading " + file);
		}
    } 		
}
